<?php

class UsersController extends Asd_Controller
{

    protected $auth = null;

    public function init()
    {
        parent::init();
        $this->view->baseUrl = $this->_request->getBaseUrl();
        $this->auth = Zend_Auth::getInstance()->hasIdentity() ? Zend_Auth::getInstance()->getIdentity() : null;
    }

    public function indexAction()
    {
        
    }

    public function registrationAction()
    {
        $this->view->title = 'Жаңы колдонуучуну катто';
        $form = new Application_Form_Registration();
        if ($this->_request->isPost())
        {   
            if ($form->isValid($this->_request->getPost()))
            {
                $data = $this->_request->getPost();
                $user = new Application_Model_Users();
                $user->fill($data);
                $user->user_password = sha1($data['user_password']);
                $user->user_birthday = time();
                $user->user_creation_date = time();
                $user->user_creation_ip   = $_SERVER['REMOTE_ADDR'];
                $user->user_language_id   = 1;
                $user->user_lastlogin_ip  = $_SERVER['REMOTE_ADDR'];
                $user->user_lastlogin_date = time();  
                $user->user_status        = 'Привет Всем!!!';
                $user->user_activ_code    = '1';
                $user->user_role_id       = 2;
                $user->user_avatar        = 'default';
                $user->save();
                $this->_redirect('users/login');
            }
        }
        $this->view->form = $form;
    }

    public function loginAction()
    {
        $this->view->title = 'Авторизация';
        $form = new Application_Form_Auth();
        $user = new Application_Model_Users();
        if ($this->_request->isPost())
        {
            if ($form->isValid($this->_request->getPost()))
            {
                if ($user->authorize($form->getValue('login'), $form->getValue('password')))
                {
                    $this->auth = Zend_Auth::getInstance()->getIdentity();
                    $auth_user = new Application_Model_Users($this->auth->user_id);
                    $auth_user->user_lastlogin_date = time();
                    $auth_user->save();
                    $this->_redirect('index/index');
                }
            }
        }
        if (Zend_Auth::getInstance()->hasIdentity())
        {
            $roles = new Application_Model_Roles();
            $role = $roles->getRole($this->auth->user_role_id);
            $this->view->role = $role;
        }
        else {
            $this->_helper->layout->disableLayout();
        }
        $this->view->form = $form;
    }

    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_redirect('users/login');
    }

    public function deleteAction()
    {
        $id = $this->_getParam('id');
        $user = new Application_Model_Users($id);
        $user->user_active_code = 0;
        $user->save();
        $this->_redirect('admin/index');
    }

    public function viewAction()
    {
        $this->view->title = 'Профильди көрүү';
        $id = $this->_getParam('id');
        if ($id == $this->auth->user_id ||
            $this->auth->user_role_id == 1){
            $user = new Application_Model_Users($id);
            $this->view->user = $user;
        }
        else {
            $this->_redirect('error/denied');
        }
        
    }

    public function editAction()
    {
        $this->view->title = 'Редактирование пользователя';
        $id = $this->_request->getParam('id');
        $user = new Application_Model_Users($id);
        $form = new Application_Form_Registration();
        
        if ($this->_request->isPost()){   
            if ($form->isValid($this->_request->getPost())){               
                $user->fill($this->_request->getPost());
                $user->save();
                $this->_redirect('users');
            } 
        } else {
                $form->populate($user->populateForm());
        }
        $this->view->form = $form;
    }

    public function editnameAction()
    {
        $this->view->title = 'Аты-жөнүм өзгөртүү';
        $id = $this->_request->getParam('id');
        $user = new Application_Model_Users($id);
        $form = new Application_Form_Name();
        
        if ($this->_request->isPost()) {
            if($form->isValid($this->_request->getPost())){
                $user->fill($this->_request->getPost());
                $user->save();
                $this->_redirect('users/view/id/' . $this->auth->user_id);
            }
        }
        else {
            $form->populate($user->populateForm());
        }
        $this->view->form = $form;
    }

    public function editemailAction()
    {
        $this->view->title = "Email'ин өзгөртүү";
        $id = $this->_request->getParam('id');
        $user = new Application_Model_Users($id);
        $form = new Application_Form_Email();
        
        if ($this->_request->isPost()){
            if ($form->isValid($this->_request->getPost())){
               $user->fill($this->_request->getPost());
               $user->save();
               $this->_redirect('users/view/id/' . $this->auth->user_id);
            }
        }
        else {
            $form->populate($user->populateForm());
        }
        $this->view->form = $form;
    }

    public function editpasswordAction()
    {
        $this->view->title = "Email'ин өзгөртүү";
        $id = $this->_request->getParam('id');
        $user = new Application_Model_Users($id);
        $form = new Application_Form_Password();
        
        if ($this->_request->isPost()){
            if ($form->isValid($this->_request->getPost())){
                $data = $this->_request->getPost();
               $user->user_password = sha1($data['user_password']);
               $user->save();
               $this->_redirect('users/view/id/' . $this->auth->user_id);
            }
        }
        $this->view->form = $form;
    }

    public function imageAction()
    {
        $this->view->title = "Сүрөттү өзгөртүү";
        $id = $this->_request->getParam('id');
        $this->view->id = $id;
        $user = new Application_Model_Users($id);
        $form = new Application_Form_Jcrop();
        
        if($this->_request->isPost()){
            if ($form->isValid($this->_request->getPost())) {
                $data = $this->_request->getPost();
                $unique = $user->user_avatar;
                if ($unique == 'default'){
                    $unique = uniqid();
                    $user->user_avatar = $unique;
                    $user->save();
//                    Zend_Auth::getInstance()->getStorage()->write($user->populateForm());
                }
                
                $targ_w = 79;
                $targ_h = 79;
                $jpeg_quality = 100;
                
                $src = 'images/temp/temp1' . $id . '.jpg';
                                
                $img_r = imagecreatefromjpeg($src);
                $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
                
                imagecopyresampled($dst_r, $img_r, 0, 0, $data['x'], $data['y'], $targ_w, $targ_h, $data['w'], $data['h']);
                if (file_exists('images/avatars/'. $unique .'.jpg')) {
                    unlink('images/avatars/'. $unique .'.jpg');
                }
                imagejpeg($dst_r, 'images/avatars/'. $unique .'.jpg', $jpeg_quality);
                $this->_redirect('users/index');
                
            }
        }
        $this->view->form = $form;
    }

    public function uploadAction()
    {
        $this->view->title = "Сүрөт жүктөө";
        $form = new Application_Form_UploadImage();
        if ($this->_request->isPost()) {
            if ($form->isValid($this->_request->getPost())) {
                
                $file = $form->file->getFileInfo();
                $ext = pathinfo($file['file']['name'], PATHINFO_EXTENSION);
                $newName = 'temp'.$this->auth->user_id.'.'.$ext;
                
                $fullFilePath = 'images/temp/' . $newName;
                $form->file->addFilter('Rename', $fullFilePath); //добавляем фильтр «Rename» к элементу формы file, где передаём новое имя + полный путь к файлу на сервере
                $form->file->receive();
                 
                $size = getimagesize($fullFilePath);
                $width = $size[0];
                $height = $size[1];
                $ratio = $width > $height ? 500 / $width : 500 / $height;
                $new_width = $width * $ratio;
                $new_height = $height * $ratio;
                
                $image_type = $size[2];
                $image = null;
                switch ($image_type) {
                    case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($fullFilePath);break;
                    case IMAGETYPE_GIF: $image = imagecreatefromgif($fullFilePath);break;
                    case IMAGETYPE_PNG: $image = imagecreatefrompng($fullFilePath);break;
                }
                $new_image = ImageCreateTrueColor($new_width, $new_height);
                imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                
                if (file_exists('images/temp/temp1'.$this->auth->user_id.'.jpg')) {
                    unlink('images/temp/temp1'.$this->auth->user_id.'.jpg');
                }
                
                imagejpeg($new_image, 'images/temp/temp1'.$this->auth->user_id.'.jpg', 100);
                unlink('images/temp/temp' . $this->auth->user_id . '.jpg');
                
                $this->_redirect('users/image/id/' . $this->auth->user_id);
            }
        }
        $this->view->form = $form;
    }

    public function calendarAction()
    {
        
    }
    public function messageAction() {
         
        $this->view->title = 'Колдонуучунун каттары';
        $message = new Application_Model_Messages();
        $this->view->messages = $message->getMessages(Zend_Auth::getInstance()->getIdentity()->user_id);
        
    }


}







